import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_ui/src/theme/colors.dart';

class CountDown extends StatefulWidget {
  final int countdown;
  final String inactiveText;
  final String reInactiveText;
  final String activePrefixText;
  final bool disabled;
  CountDown({ Key key, this.countdown, this.inactiveText, this.reInactiveText, this.activePrefixText, this.disabled = false}) : super(key: key);

  _CountDownState createState() => _CountDownState();
}

enum CountDownStatus {
  inactive,
  active,
  reInactive,
}

class _CountDownState extends State<CountDown> {
  Timer timer;
  int secound;
  CountDownStatus status;

  buildCountDownText() {
    String inactiveText = widget.inactiveText;
    String reInactiveText = widget.reInactiveText;
    String activePrefixText = widget.activePrefixText;
    switch (status) {
      case CountDownStatus.inactive:
        return Text(inactiveText ??= "获取验证码",style: TextStyle(color: PrimaryColor));
        break;
      case CountDownStatus.active:
        return Text("${activePrefixText ??= "已发送"}${secound}s",style: TextStyle(color: DescColor));
        break;
      case CountDownStatus.reInactive:
        return Text(reInactiveText ??= "重新发送",style: TextStyle(color: PrimaryColor));
        break;
      default:
        break;
    }
    return Text("获取验证码",style: TextStyle(color: PrimaryColor));
  }

  _startTimer() {
    timer?.cancel();
    secound = widget.countdown;
    status = CountDownStatus.active;
    timer = Timer.periodic(Duration(seconds: 1), (_timer){
      if (secound == 0) {
        status = CountDownStatus.reInactive;
      }
      secound -= 1;
      setState(() {});
    });
    setState(() {});
  }
  
  @override
  Widget build(BuildContext context) {
    return InkWell(
       child: buildCountDownText(),
       onTap: widget.disabled || <CountDownStatus>[CountDownStatus.active].contains(status)  ? null : () {
        _startTimer();
       },
    );
  }
}